package mobile

import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*
import wyd.WydCategory

Date now = new Date()
Entity transcation = null
if(params.transcationKey == 'New') {
	transcation = new Entity('TranscationE')
}
else {
	def transcationId = params.transcationKey as int
	def transcationKey = ['TranscationE', transcationId] as Key
	transcation = datastore.get(transcationKey)
}

transcation.amount = params.transcationAmount as float
transcation.description = params.transcationDescription
transcation.userId = session.user.id
try {
	def s = "$params.transcationCreatedDateStg $params.transcationCreatedTimeStg"
	def createdTime = new Date().parse('yyyy-MM-dd HH:mm', s)
	use(groovy.time.TimeCategory) {
		int timeZoneHour = session.userTimeZoneHour as int
		int timeZoneMinute = session.userTimeZoneMinute as int
		transcation.createdTime = createdTime - timeZoneHour.hours - timeZoneMinute.minutes
	}
} catch(Throwable t) {
	t.printStackTrace()
	transcation.createdTime = now
}
transcation.updatedTime = now
transcation.save()

if(params.transcationKey != 'New') {
	def query = new Query('TranscationTagE')
	query.addSort('name', Query.SortDirection.ASCENDING)
	query.addFilter('transcationId', Query.FilterOperator.EQUAL, transcation.key.id)
	query.addFilter('userId', Query.FilterOperator.EQUAL, session.user.id)
	PreparedQuery preparedQuery = datastore.prepare(query)
	def ttentities = preparedQuery.asList( withLimit(Integer.MAX_VALUE) )
	ttentities.each { transcationTag ->
		transcationTag.delete()
	}
}

if(params.transcationTags != null) {
	params.transcationTags.tokenize('#').each { tag ->
		Entity transcationTag = new Entity('TranscationTagE')
		transcationTag.name = tag.trim()
		transcationTag.transcationId = transcation.key.id
		transcationTag.userId = session.user.id
		transcationTag.createdTime = now
		transcationTag.updatedTime = now
		transcationTag.save()
	}
}

memcache.delete(session.user.id + '-todayTranscations')
memcache.delete(session.user.id + '-weekTranscations')
memcache.delete(session.user.id + '-monthTranscations')

forward 'expenses.groovy'